package com.caiheng.api.service.sys.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.estate.EstateUserMapper;
import com.caiheng.api.dao.sys.SysDeptMapper;
import com.caiheng.api.entity.estate.EstateUser;
import com.caiheng.api.entity.sys.SysDept;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.sys.SysDeptService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小区的部门关联的事项类型，为了区分一个部门可能存在多项智能的情况，比如合并巡检和巡更Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-03
 */
@Service
public class SysDeptServiceImpl extends BaseServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private EstateUserMapper estateUserMapper;

    @Override
    public List<SysDept> selectDeptListByEstateAndEventType(Map<String, Object> map) {
        return sysDeptMapper.selectDeptListByEstateAndEventType(map);
    }

    @Override
    public boolean isDeptUserBySysUserId(SysUser sysUser, int eventType) {
        int isPerm = 0;
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("estateId", sysUser.getEstateId());
        mapParam.put("eventType", 2);
        List<Integer> deptIdList = new ArrayList<>();
        List<SysDept> deptList = selectDeptListByEstateAndEventType(mapParam);
        if(CollUtil.isNotEmpty(deptList)){
            for (SysDept sysDept : deptList) {
                deptIdList.add(sysDept.getDeptId());
            }
            QueryWrapper<EstateUser> qwUser = new QueryWrapper<>();
            qwUser.eq("estate_id", sysUser.getEstateId());
            qwUser.eq("sys_user_id", sysUser.getUserId());
            qwUser.in("dept_id", deptIdList);
            qwUser.last("limit 1");
            EstateUser estateUser = estateUserMapper.selectOne(qwUser);
            if(estateUser != null){
                isPerm = 1;
            }
        }
        return isPerm == 1;
    }
}
